﻿#include "qttools.h"

#include <QDir>
#include <QCoreApplication>
#include <QEventLoop>
#include <QElapsedTimer>
#include <QFileInfo>
#include <QFile>
#include <QDate>
#include <QLocale>
#include <QDebug>

#include <QRegExp>
#include <QStringList>

/* 用于MOUBUS协议中CRC校验的数组 */
static const quint16 s_nCRCTableAbs[] = {
    0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401,
    0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400,
};

const quint8  auchCRCHi[] = {
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
    0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
    0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
    0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
    0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
    0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
    0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
    0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
    0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
    0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
};

const quint8  auchCRCLo[] = {
    0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
    0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
    0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
    0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
    0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
    0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
    0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
    0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
    0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
    0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
    0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
    0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
    0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
    0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
    0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
    0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
    0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
    0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
    0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
    0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
    0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
    0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
    0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
    0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
    0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
    0x43, 0x83, 0x41, 0x81, 0x80, 0x40
};

QString QtTools::m_strAppPath = QDir::currentPath() + "/";
QString QtTools::m_strConfPath = m_strAppPath + "conf/";
QString QtTools::m_strIconsPath = m_strAppPath + "icons/";
QString QtTools::m_strWallpaperPath = m_strAppPath + "wallpapers/";
QString QtTools::m_strDesktopFilePath = m_strAppPath + "apps/";

QString QtTools::fileSize(qint64 size)
{
    if (size > GB_SIZE)
    {
        return QString("%1 GB").arg(size * 1.0 / GB_SIZE, 0, 'f', 1);
    }
    else if(size > MB_SIZE)
    {
        return QString("%1 MB").arg(size * 1.0 / MB_SIZE, 0, 'f', 1);
    }
    else if(size > KB_SIZE)
    {
        return QString("%1 KB").arg(size * 1.0 / KB_SIZE, 0, 'f', 1);
    }

    return QString::number(size) + " Byte";
}

QDate QtTools::buildDate(QString _date)
{
    return QLocale(QLocale::English).toDate(_date.replace("  ", " "), "MMM dd yyyy");
}

void QtTools::getVersion(QString *_ver, QString *_date, QString *_time)
{
    *_ver =  "1.0.0.1";
    *_date = buildDate(__DATE__).toString("yyyy-MM-dd");
    *_time = __TIME__;
}

void QtTools::msSleep(int _msc)
{
    QElapsedTimer timer;
    timer.start();

    while(timer.elapsed() < _msc ) {
        QCoreApplication::processEvents(QEventLoop::AllEvents, _msc);
    }
}

void QtTools::checkDir(const QString &_dir)
{
    QDir dir(m_strAppPath + _dir);
    if (!dir.exists()) {
        dir.mkpath(dir.path());
    }
}

void QtTools::checkDirs(QStringList _dirs)
{
    initAppPath();

    for (int i = 0; i < _dirs.size(); i++) {
        checkDir(_dirs.at(i));
    }
}

void QtTools::initAppPath()
{
    m_strAppPath = qApp->applicationDirPath() + "/";
    m_strConfPath = m_strAppPath + "conf/";
    m_strIconsPath = m_strAppPath + "icons/";
    m_strWallpaperPath = m_strAppPath + "wallpapers/";
    m_strDesktopFilePath = m_strAppPath + "apps/";
}

void QtTools::clearDir(const QString &_path)
{
    QDir dir(_path);
    qDebug() << "Clear path" << _path;
    QFileInfoList files = dir.entryInfoList(QDir::Files);
    foreach(QFileInfo file, files) {
        if (file.isDir()) {
            clearDir(file.absolutePath());
        } else {
            QFile::remove(file.absoluteFilePath());
        }
    }
}


quint16 QtTools::MODBUS_CRC16(quint8 *pushdata, quint8 length)
{
    quint8 uchCRCHi = 0xFF;
    quint8 uchCRCLo = 0xFF;
    quint8 uIndex;
    while (length--)
    {
        uIndex = uchCRCHi ^ *pushdata++;
        uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex];
        uchCRCLo = auchCRCLo[uIndex];
    }

    return (uchCRCHi << 8 | uchCRCLo);
}

bool QtTools::isBigEndian()
{
    /*定义一个2个字节长度的数据，并赋值为1,则n的16进制表示为0x0001
    如果系统以“大端”存放数据，也即是以MSB方式存放，那么低字节存放的必定是0x00，高字节存放的必定是0x01
    如果系统以“小端”存放数据，也即是以LSB方式存放，那么低字节存放的必定是0x01，高字节存放的必定是0x00
    所谓MSB，就是将最重要的位存入低位，而LSB则是将最不重要的位存入低位
    我们可以通过检测低位的数值就可以知道系统的字节序
    */
    int a=1;
    char *pa=(char *)&a;
    if(0x01 == (*pa & 0xFF)) {
        return false;
    }

    return true;
}


QByteArray QtTools::baFromFloatBigEndian(float _f)
{
    char* pch = (char*)(&_f);

    QByteArray ret;
    if (isBigEndian()) {
        for (int var = 0; var < 4; ++var) {
            ret.append((*(pch+var)) & 0xFF);
        }
    } else {
        for (int var = 3; var >= 0; --var) {
            ret.append((*(pch+var)) & 0xFF);
        }
    }

    return ret;
}

QByteArray QtTools::baFromUint32BigEndian(const quint32 _ustate)
{
    QByteArray ret;
    for (int var = 3; var >= 0; --var) {
        ret.append((_ustate >> (8*var)) & 0xFF);
    }
    return ret;
}

QByteArray QtTools::baFromUint16BigEndian(const quint16 _id)
{
    QByteArray ret;
    ret.append((_id >> 8) & 0xFF);
    ret.append(_id & 0xFF);
    return ret;
}

float QtTools::floatFromByteArray(QByteArray arr)
{
    if (4 != arr.length()) {
        return 0.0f;
    }

    float ret;
    char* pch = (char*)(&ret);

    if (isBigEndian()) {
        for (int var = 0; var < 4; ++var) {
            *pch++ = arr.at(var) ;
        }
    } else {
        for (int var = 0; var < 4; ++var) {
            *pch++ = arr.at(3-var) ;
        }
    }

    return ret;
}

// QByteArray 高位在前的二进制数
quint32 QtTools::uint32FromByteArray(QByteArray arr)
{
    if (4 != arr.length()) {
        return 0;
    }

    quint32 ret = 0;
    for (int var = 0; var < 4; ++var) {
        ret += ((arr.at(var) & 0xFF) << (8*(3-var)));
    }
    return ret;
}

quint64 QtTools::uint64FromByteArray(QByteArray arr)
{
    if (8 != arr.length()) {
        return 0;
    }

    quint64 ret = 0;
    for (int i = 0; i < 8; i++)
    {
        ret |= ((quint64)(arr.at(i) & 0xFF) << (8 * (7 - i)));
    }

    return ret;
}

qint16 QtTools::int16FromByteArray(QByteArray data)
{
    if (2 != data.length()) {
        return 0;
    }

    qint16 ret = ((uchar)data[1] << 8) & 0xffff;
    ret |= ((uchar)data[0]);

    return ret;
}

float QtTools::floatFromHL(quint16 hvalue, quint16 lvalue)
{
    float fv = 0;
    char* pch = (char*)(&fv);
    if (isBigEndian()) {
        *pch++ = (hvalue >> 8) & 0xff;
        *pch++ = hvalue & 0xff;
        *pch++ = (lvalue >> 8) & 0xff;
        *pch++ = lvalue & 0xff;
    } else {
        *pch++ = lvalue & 0xff;
        *pch++ = (lvalue >> 8) & 0xff;
        *pch++ = hvalue & 0xff;
        *pch++ = (hvalue >> 8) & 0xff;
    }

    return fv;
}

/**
 * @brief QtTools::GetCRCData
 * 获取CRC校验和
 * @param data
 * @return
 */
quint16 QtTools::GetCrcData(const QByteArray &data)
{
    quint16 nCrcRet = 0xFFFF;

    uchar uchTemp;
    for (int i = 0; i < data.length(); i++) {
        uchTemp = data[i];
        nCrcRet = s_nCRCTableAbs[(uchTemp ^ nCrcRet) & 15] ^ (nCrcRet >> 4);
        nCrcRet = s_nCRCTableAbs[((uchTemp >> 4) ^ nCrcRet) & 15] ^ (nCrcRet >> 4);
    }

    return nCrcRet;
}

QByteArray QtTools::GetCRCData(const QByteArray &data)
{
    quint16 nCrcRet = GetCrcData(data);
    QByteArray byRet;
    byRet[0] = (nCrcRet >> 8) & 0xff;
    byRet[1] = (nCrcRet >> 0) & 0xff;
    return byRet;
}

/**
 * @brief QtTools::Size
 * 文件大小单位转换
 * @param bytes
 * @return
 */
QString QtTools::Size(qint64 bytes)
{
    QString strUnit;
    double dSize = bytes * 1.0;
    if (dSize <= 0)
    {
        dSize = 0.0;
    }
    else if (dSize < 1024)
    {
        strUnit = "Bytes";
    }
    else if (dSize < 1024 * 1024)
    {
        dSize /= 1024;
        strUnit = "KB";
    }
    else if (dSize < 1024 * 1024 * 1024)
    {
        dSize /= (1024 * 1024);
        strUnit = "MB";
    }
    else
    {
        dSize /= (1024 * 1024 * 1024);
        strUnit = "GB";
    }

    return QString("%1 %2").arg(QString::number(dSize, 'f', 2)).arg(strUnit);
}

/**
 * @brief QtTools::Speed
 * 速度转换
 * @param speed
 * @return
 */
QString QtTools::Speed(double speed)
{
    QString strUnit;
    if (speed <= 0)
    {
        speed = 0;
        strUnit = "Bytes/S";
    }
    else if (speed < 1024)
    {
        strUnit = "Bytes/S";
    }
    else if (speed < 1024 * 1024)
    {
        speed /= 1024;
        strUnit = "KB/S";
    }
    else if (speed < 1024 * 1024 * 1024)
    {
        speed /= (1024 * 1024);
        strUnit = "MB/S";
    }
    else
    {
        speed /= (1024 * 1024 * 1024);
        strUnit = "GB/S";
    }

    QString strSpeed = QString::number(speed, 'f', 2);
    return QString("%1 %2").arg(strSpeed).arg(strUnit);
}

/**
 * @brief QtTools::TimeFormat
 * 计算下载时间
 * @param seconds
 * @return
 */
QString QtTools::TimeFormat(int seconds)
{
    QString strValue;
    QString strSpacing(" ");
    if (seconds <= 0)
    {
        strValue = QString("%1s").arg(0);
    }
    else if (seconds < 60)
    {
        strValue = QString("%1s").arg(seconds);
    }
    else if (seconds < 60 * 60)
    {
        int nMinute = seconds / 60;
        int nSecond = seconds - nMinute * 60;

        strValue = QString("%1m").arg(nMinute);

        if (nSecond > 0)
            strValue += strSpacing + QString("%1s").arg(nSecond);
    }
    else if (seconds < 60 * 60 * 24)
    {
        int nHour = seconds / (60 * 60);
        int nMinute = (seconds - nHour * 60 * 60) / 60;
        int nSecond = seconds - nHour * 60 * 60 - nMinute * 60;

        strValue = QString("%1h").arg(nHour);

        if (nMinute > 0)
            strValue += strSpacing + QString("%1m").arg(nMinute);

        if (nSecond > 0)
            strValue += strSpacing + QString("%1s").arg(nSecond);
    }
    else
    {
        int nDay = seconds / (60 * 60 * 24);
        int nHour = (seconds - nDay * 60 * 60 * 24) / (60 * 60);
        int nMinute = (seconds - nDay * 60 * 60 * 24 - nHour * 60 * 60) / 60;
        int nSecond = seconds - nDay * 60 * 60 * 24 - nHour * 60 * 60 - nMinute * 60;

        strValue = QString("%1d").arg(nDay);

        if (nHour > 0)
            strValue += strSpacing + QString("%1h").arg(nHour);

        if (nMinute > 0)
            strValue += strSpacing + QString("%1m").arg(nMinute);

        if (nSecond > 0)
            strValue += strSpacing + QString("%1s").arg(nSecond);
    }

    return strValue;
}



//16进制字符串转字节数组
QByteArray QtTools::HexStrToByteArray(QString str)
{
    QByteArray senddata;
    int hexdata,lowhexdata;
    int hexdatalen = 0;
    int len = str.length();
    senddata.resize(len/2);
    char lstr,hstr;
    for(int i=0; i<len; )
    {
        hstr=str[i].toLatin1();
        if(hstr == ' ')
        {
            i++;
            continue;
        }
        i++;
        if(i >= len)
            break;
        lstr = str[i].toLatin1();
        hexdata = ConvertHexChar(hstr);
        lowhexdata = ConvertHexChar(lstr);
        if((hexdata == 16) || (lowhexdata == 16))
            break;
        else
            hexdata = hexdata*16+lowhexdata;
        i++;
        senddata[hexdatalen] = (char)hexdata;
        hexdatalen++;
    }
    senddata.resize(hexdatalen);
    return senddata;
}

// 转换16进制数据为字符型
char QtTools::ConvertHexChar(char ch)
{
    if((ch >= '0') && (ch <= '9'))
        return ch-0x30;
    else if((ch >= 'A') && (ch <= 'F'))
        return ch-'A'+10;
    else if((ch >= 'a') && (ch <= 'f'))
        return ch-'a'+10;
    else return (-1);
}


// 判断是否是IP地址
bool QtTools::IsIpAddr(const QString &strIp)
{
    QRegExp RegExp("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)");
    return RegExp.exactMatch(strIp);
}
